<template>
  <a-spin tip="Loading..." :spinning="loading">
    <a-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px" v-if="visible">
      <a-col :md="12" :sm="24">
        <a-card :bordered="false">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :xl="10" :lg="6" :md="6" :sm="24">
                <a-form-item label="经销商编号">
                  <a-input placeholder="请输入编号模糊查询" v-model="queryParam.custCode"></a-input>
                </a-form-item>
              </a-col>
              <a-col :xl="10" :lg="6" :md="6" :sm="24">
                <a-form-item label="经销商名称">
                  <a-input placeholder="请输入名称模糊查询" v-model="queryParam.custName"></a-input>
                </a-form-item>
              </a-col>
              <!--<a-col :xl="7" :lg="6" :md="6" :sm="24">-->
              <!--<a-form-item label="职位等级">-->
              <!--<a-input placeholder="请输入等级模糊查询" v-model="queryParam.positionLevel"></a-input>-->
              <!--</a-form-item>-->
              <!--</a-col>-->

              <div style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-col :xl="4" :lg="6" :md="6" :sm="24">
                  <a-button type="primary" @click="onSearch" icon="search">查询</a-button>
                </a-col>
              </div>
            </a-row>
          </a-form>
          <a-table
            ref="table"
            size="middle"
            class='Table'
            bordered
            :scroll="{
          x:'max-content'
        }"
            tableLayout="auto"
            rowKey="custCode"
            :columns="custsColumns"
            :dataSource="custs"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: custSelectedRowKeys,
                                        onSelect: onSelect,onSelectAll:onSelectAll}"
            @change="handleTableChange"
          >

            <template slot="mainCustomer" slot-scope="text, record, index" v-if="false">
              {{text}}
            </template>
            <template slot="imgUrl" slot-scope="text, record, index">
              <div class="anty-img-wrap">
                <a-avatar shape="square" :src="record.imgUrl" icon="user"/>
              </div>
            </template>

            <template slot="status" slot-scope="text">{{ text | isActiveStatus }}</template>
          </a-table>

        </a-card>
      </a-col>
      <a-col :md="12" :sm="24">
        <a-card :bordered="false">
          <a-table
            ref="table"
            size="middle"
            class='Table'
            bordered
            :scroll="{
          x:'max-content'
        }"
            tableLayout="auto"
            rowKey="custCode"
            :columns="custsDataColumns"
            :dataSource="custsData"
          >

            <template slot="mainCustomer" slot-scope="text, record, index">
              <a-radio-group v-model="record.mainCustomer" @change="onPositionChange">
                <a-radio :value="0">
                  主职
                </a-radio>
                <a-radio :value="1">
                  副职
                </a-radio>
              </a-radio-group>
            </template>
            <template slot="imgUrl" slot-scope="text, record, index">
              <div class="anty-img-wrap">
                <a-avatar shape="square" :src="record.imgUrl" icon="user"/>
              </div>
            </template>

            <template slot="status" slot-scope="text">{{ text | isActiveStatus }}</template>

            <template slot="action" slot-scope="text, record, index">
              <a @click="handleDelete(record)">删除</a>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </a-spin>
</template>

<script>
  import {filterObj} from '@/utils/util'
  import {getAction, postAction} from "@api/manage";

  export default {
    name: "SelectCustomer",
    props: {
      currentData: Array,
      visible: Boolean
    },
    activated() {
      console.log('aaaa')
    },
    mounted() {
      this.loadData(1)
    },
    data() {
      return {

        /* 排序参数 */
        isorter: {
          column: 'createTime',
          order: 'desc',
        },
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '40', '50'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        activeKey: 'cust',
        typeLoading: false,
        queryParam: {},

        custs: [],
        custsColumns: [
          {
            title: '#',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
          },
          {
            title: '经销商编号',
            align: 'center',
            dataIndex: 'custCode'
          },
          {
            title: '经销商名称',
            align: 'center',
            dataIndex: 'custName'
          },
          // {
          //     title: '职位级别',
          //     align: 'center',
          //     dataIndex: 'positionLevel'
          // },
          // {
          //     title: '操作',
          //     align: 'center',
          //     dataIndex: 'action',
          //     width: 80,
          //     ellipsis: true,
          //     scopedSlots: {customRender: 'action'},
          // },
        ],
        custsDataColumns: [
          {
            title: '#',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
          },
          {
            title: '经销商编号',
            align: 'center',
            dataIndex: 'custCode'
          },
          {
            title: '经销商名称',
            align: 'center',
            dataIndex: 'custName'
          },
          // {
          //     title: '职位级别',
          //     align: 'center',
          //     dataIndex: 'positionLevel'
          // },
          // {
          //     title: '职位类型',
          //     align: 'center',
          //     dataIndex: 'mainPosition',
          //     scopedSlots: {customRender: 'mainPosition'},
          // },
          {
            title: '操作',
            align: 'center',
            dataIndex: 'action',
            width: 80,
            ellipsis: true,
            scopedSlots: {customRender: 'action'},
          },
        ],
        custSelectedRowKeys: [],
        custSelectionRows: [],
        loading: false,
        userInfo: this.$store.getters.userInfo,
        record: null,

      }
    },
    computed: {
      custsData: {
        get() {
          this['custSelectedRowKeys'] = this.currentData.map(row => row.custCode);
          this['custSelectionRows'] = this.currentData
          return this.currentData
        },
        set(v) {
          // this['positionSelectedRowKeys'] = v.map(row => row.positionCode);
          // this['positionSelectionRows'] = v
          this.$emit('currentData:update', v)
        }
      }
    },
    created() {
      // 该方法触发屏幕自适应
      this.resetScreenSize();
    },
    methods: {
      /**
       * 删除已选中商品
       * @param record
       */
      handleDelete(record) {
        this[this.activeKey + 'sData'].removeByCode(record, this.activeKey + 'Code')
        this[this.activeKey + 'SelectionRows'].removeByCode(record, this.activeKey + 'Code')
        this[this.activeKey + 'SelectedRowKeys'].remove(record[this.activeKey + 'Code'])
      },
      // 触发屏幕自适应
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.scrollTrigger = {x: 800};
        } else {
          this.scrollTrigger = {};
        }
      },
      /**
       * 获取查询参数
       * @returns {*}
       */
      getQueryParams() {
        let param = Object.assign({}, this.queryParam);
        param.current = this.ipagination.current;
        param.size = this.ipagination.pageSize;
        return filterObj(param);
      },
      searchReset(num) {
        let that = this;
        if (num !== 0) {
          that.loadData(1);
        }
        that[this.activeKey + 'SelectedRowKeys'] = [];
        that[this.activeKey + 'SelectionRows'] = [];
        that[this.activeKey + 'sData'] = []
      },
      /**
       * 手动全选/取消全选分类
       * @param selected
       * @param selectedRows
       * @param changeRows
       */
      onSelectAll(selected, selectedRows, changeRows) {
        this[this.activeKey + 'SelectedRowKeys'] = selectedRows.map(row => row.code);
        this[this.activeKey + 'SelectionRows'] = selectedRows
        if (selected) {
          //todo 选中
          changeRows.map(row => {
            this[this.activeKey + 'sData'].push(row)
          })
        } else {
          //todo 取消选中
          changeRows.map(row => {
            this[this.activeKey + 'sData'].removeByCode(row, this.activeKey + 'Code')
          })
        }
      },

      /**
       * 手动勾选/取消分类
       * @param record
       * @param selected
       * @param selectedRows
       * @param nativeEvent
       */
      onSelect(record, selected, selectedRows, nativeEvent) {
        this[this.activeKey + 'SelectedRowKeys'] = selectedRows.map(row => row[this.activeKey + 'Code']);
        this[this.activeKey + 'SelectionRows'] = selectedRows.slice(0)
        if (selected) {
          //todo 选中
          this[this.activeKey + 'sData'].push({...record})
        } else {
          //todo 取消选中
          this[this.activeKey + 'sData'].removeByCode(record, this.activeKey + 'Code')
        }


      },
      onSearch() {
        this.loadData(1);
      },

      /**
       * 覆盖mixin的loadData方法
       * @param arg
       * @returns {Promise<void>}
       */
      async loadData(arg) {

        if (arg === 1) {
          this.ipagination.current = 1;
        }
        let url = '/customerController/getPageList'
        this.loading = true
        let params = this.getQueryParams()//查询条件
        await postAction(url, {...params}).then((res) => {
          if (res.success) {
            this[this.activeKey + 's'] = res.result.records.map(row => Object.assign({}, row, {
              mainCustomer: 0
            }))
            this.ipagination.total = res.result.total
          }
        }).finally(() => {
          this.loading = false
        })
      },

      handleTableChange(pagination, filters, sorter) {
        console.log(pagination)
        //分页、排序、筛选变化时触发
        //TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.ipagination = pagination;
        this.loadData();
      },
      //
      // setData(){
      //     this.$emit('getPosition',this.positionsData)
      // }
    },
  }
</script>

<style scoped>

</style>
